#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <getopt.h>

#define PROGRAM_NAME "myget"

static struct option const long_opts[] = {
        {"output-document", required_argument, NULL, 'O'},
        {"debug",           no_argument,       NULL, 'd'},
        {"version",         no_argument,       NULL, 'V'},
        {"help",            no_argument,       NULL, 'h'},
        {NULL,              0,                 NULL, 0}
};

void usage(int status) {
    printf("Usage: %s [OPTION]... [URL]...\n", PROGRAM_NAME);

    if (status != 0) {
        fprintf(stderr, "Try '%s --help' for more information.\n", PROGRAM_NAME);
    } else {
        fprintf(stdout, "  -O,  --output-document=FILE  write documents to FILE\n");
        fprintf(stdout, "  -d,  --debug                 print debug output\n");
        fprintf(stdout, "  -h,  --help                  display this help and exit\n");
        fprintf(stdout, "  -V,  --version               output version information and exit\n");
    }

    exit(status);
}

int main(int argc, char *argv[]) {
    int  optc;
    char *filename = NULL;
    bool debug     = false;

    while ((optc = getopt_long(argc, argv, "O:dVh", long_opts, NULL)) != -1) {
        printf("optc:%c\toptarg:%s\toptind:%d\n", optc, optarg, optind);

        switch (optc) {
            case 'O':
                filename = optarg;
                break;
            case 'd':
                debug = true;
                break;
            case 'V':
                printf("%s 0.0.1\n", PROGRAM_NAME);
                exit(0);
            case 'h':
                usage(0);
                break;
            case '?':
                usage(1);
                break;
        }
    }

    if (optind + 1 != argc) {
        usage(1);
    }

    const char *url = argv[optind];

    printf("url\t%s\nfilename\t%s\ndebug\t%d\n", url, filename, debug);

    return 0;
}

